package com.hmdp.service.impl;

import com.hmdp.entity.BlogComments;
import com.hmdp.mapper.BlogCommentsMapper;
import com.hmdp.service.IBlogCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class BlogCommentsServiceImpl extends ServiceImpl<BlogCommentsMapper, BlogComments> implements IBlogCommentsService {

    @Autowired
    private BlogCommentsMapper blogCommentsMapper;

    @Override
    public List<BlogComments> showComments(Long blogId) {
        //找出探店的所有评论
        List<BlogComments> blogComments = blogCommentsMapper.getComments(blogId);

        //找出所有顶级评论
        List<BlogComments> rootComments = blogComments.stream().
                filter(comment -> comment.getParentId() == 0).collect(Collectors.toList());

        // 获取回复评论，优化流操作，避免多次循环
        Map<Long, BlogComments> commentsMap = blogComments.stream().collect(Collectors.toMap(BlogComments::getId, v -> v));

        // 遍历一级评论，获取对应的回复评论,并设置回复评论对应的父级评论的信息 图像和昵称
        for (BlogComments rootComment : rootComments) {
            //获取顶级评论的所有回复
            List<BlogComments> childComments = blogComments.stream().
                    filter(blogComment -> blogComment.getParentId().equals(rootComment.getId())).collect(Collectors.toList());

            //设置回复的评论的父级评论的信息
            for (BlogComments childComment : childComments) {
                //获取父级评论的头像和昵称
                BlogComments parentComment = commentsMap.get(childComment.getParentId());
                String parentNickName = parentComment.getNickName();
                String parentIcon = parentComment.getIcon();

                childComment.setPNickName(parentNickName);
                childComment.setPIcon(parentIcon);
            }

            //将所有回复的评论添加到顶级评论的子评论中
            rootComment.setChildComments(childComments);
        }
        return  rootComments;

    }
}
